package com.szxydb.dmp.utils;

import com.szxydb.dmp.admin.system.model.SystemConfig;
import com.szxydb.dmp.constants.RegularConstants;
import com.szxydb.dmp.exception.CrmebException;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

public class ValidateFormUtil {

    public static void checkType(SystemConfig systemConfig, String rule){
        if (StringUtils.isBlank(rule)){
            return;
        }
        List<String> list = CrmebUtil.stringToArrayStr(rule);

        for (String value : list){
            List<String> val = CrmebUtil.stringToArrayStrRegex(value,":");

            if (val.get(0).equals("required") && val.get(1).equals("true")){
                continue;
            }

            if (val.get(0).equals("number") && val.get(1).equals("true")){
                isNumber(systemConfig.getValue(),systemConfig.getTitle());
                continue;
            }

            if (val.get(0).equals("max")){
                isNumber(systemConfig.getValue(),systemConfig.getTitle());
                continue;
            }

            if (val.get(0).equals("min")){
                isNumber(systemConfig.getValue(),systemConfig.getTitle());
                continue;
            }

            if (val.get(0).equals("email") && val.get(1).equals("true")){
                isEmail(systemConfig.getValue(),systemConfig.getTitle());
                continue;
            }

            if (val.get(0).equals("phone") && val.get(1).equals("true")){
                isPhone(systemConfig.getValue(),systemConfig.getTitle());
            }
        }
    }

    public static void isRequire(String value,String info){
        if (StringUtils.isBlank(value)){
            throw new CrmebException("请填写/选择"+info);
        }
    }

    public static void isNumber(String value,String info){

    }

    public static void regularException(String value,String info,String regular,String title){
        if (!regular(value,info,regular)){
            throw new CrmebException(info + " 格式必须为 "+ title);
        }
    }

    public static boolean regular(String value,String info,String regular){
        isRequire(value,info);
        Pattern pattern = Pattern.compile(regular);
        return pattern.matcher(value).matches();
    }

    public static void isEmail(String value,String info){
        regularException(value,info, RegularConstants.EMAIL,"邮箱");
    }

    public static void isPhone(String value,String info){
        regularException(value,info,RegularConstants.PHONE,"手机");
    }
}
